<template>
    <div class="container">
        <!-- 登记原木按钮 -->
        <div class="header">
            <!-- 搜索框 -->
            <a-input-search v-model:value="searchText" placeholder="输入搜索条件" @search="handleSearch"
                style="width: 200px; margin-right: 16px" />

            <!-- 按钮组 -->
            <a-button type="primary" @click="addWoodStock">登记原木</a-button>
            <!-- <a-button type="default" @click="batchRegisterAVE" style="margin-left: 8px;">批量登记AVE</a-button>
            <a-button type="default" @click="batchRegisterCITES" style="margin-left: 8px;">批量登记CITES</a-button> -->
        </div>

        <!-- 列表页 -->
        <ATable :scroll="{ x: 2000 }" :columns="columns" :dataSource="data" :pagination="pagination" rowKey="ID"
            bordered @change="handleTableChange">
            <template #bodyCell="{ column, record }">
                <!-- 检查是否是 'action' 列 -->
                <template v-if="column.dataIndex === 'action'">
                    <a-upload v-if="record.is_offline" v-model:fileList="fileList" :beforeUpload="beforeUpload"
                        :action="action_url" :data="{ woodId: record.ID, userId: userInfo.ID }" :showUploadList="false"
                        :multiple="false" @change="handleFileChange">
                        <a-button type="primary">附件</a-button>
                    </a-upload>

                    <a-button v-if="record.is_offline" type="primary" danger style="margin-left: 5px;"
                        @click="confirmDelWoodStockDialog(record)">删除</a-button>
                    <span v-if="!record.is_offline">-</span>
                </template>
                <!-- 默认渲染其他列的内容 -->
                <template v-else>
                    {{ record[column.dataIndex] }}
                </template>
            </template>
        </ATable>
        <!-- 弹出框 -->
        <a-modal v-model:open="isModalVisible" title="新原木登记" @ok="handleOk" @cancel="handleCancel" ok-text="保存"
            cancel-text="取消" width="800px">
            <a-form :model="form" :label-col="{ style: 'width: 120px;' }" :rules="rules" ref="formRef">
                <!-- 表单项每行两个 -->
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="原木编号" name="WOOD_NO" required labelAlign="right">
                            <a-input v-model:value="form.WOOD_NO" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="仓库位置" name="NOW_DEPT_ID" required labelAlign="right">
                            <a-select v-model:value="form.NOW_DEPT_ID" :options="deptOptions" @change="handleDeptChange"
                                :filterOption="filterOption" showSearch>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="Φmoy(平均直径)" name="DIAM_AVG" labelAlign="right">
                            <a-input v-model:value="form.DIAM_AVG" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="Lg(长度)" name="WOOD_LENGTH" labelAlign="right">
                            <a-input v-model:value="form.WOOD_LENGTH" />
                        </a-form-item>
                    </a-col>

                </a-row>

                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="Vol.(方量)" name="WOOD_VOLUME" labelAlign="right">
                            <a-input v-model:value="form.WOOD_VOLUME" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="Φ1(直径)" name="DIAM1" labelAlign="right">
                            <a-input v-model:value="form.DIAM1" />
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-form-item label="Φ2(直径)" name="DIAM2" labelAlign="right">
                            <a-input v-model:value="form.DIAM2" />
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-modal>
        <a-modal v-model:open="showDelWoodStockDialog" title="你确定要删除这条记录吗?" @ok="delWoodStock"
            @cancel="cancelDelWoodStock()" ok-text="确定" cancel-text="取消" ok-type="danger">
        </a-modal>
    </div>
</template>

<script>
import { message as AMessage, Table as ATable, Modal } from "ant-design-vue";
import { ipc } from "@/utils/ipcRenderer";
import { ipcApiRoute, specialIpcRoute } from "@/api/main";
export default {
    components: {
        ATable, // 在这里注册组件
    },
    data() {
        return {
            userInfo: {},
            action_url: "",
            fileList: [],
            delWoodId: '',
            showDelWoodStockDialog: false,
            searchText: '',
            data: [], // 列表数据
            deptOptions: [],
            pagination: {
                current: 1,
                pageSize: 10,
                total: 0,
            },
            isModalVisible: false,
            form: {},
            rules: {
                WOOD_NO: [{ required: true, message: "请输入原木编号" }],
                NOW_DEPT_ID: [{ required: true, message: "请选择仓库位置" }],
                // 其他表单校验规则
            },
            columns: [
                {
                    title: "操作",
                    width: 170,
                    dataIndex: "action",
                },
                {
                    title: "钢印号",
                    dataIndex: "WOOD_NO",
                    width: 80,
                    key: "WOOD_NO",
                },
                {
                    title: "AVE",
                    dataIndex: "AVE",
                    width: 80,
                    key: "AVE",
                },
                {
                    title: "CITES",
                    dataIndex: "CITE",
                    width: 80,
                    key: "CITE",
                },
                {
                    title: "Φ1(直径)",
                    dataIndex: "DIAM1",
                    width: 100,
                    key: "DIAM1",
                },
                {
                    title: "Φ2(直径)",
                    dataIndex: "DIAM2",
                    width: 100,
                    key: "DIAM2",
                },
                {
                    title: "Φmoy(平均直径)",
                    dataIndex: "DIAM_AVG",
                    width: 130,
                    key: "DIAM_AVG",
                },
                {
                    title: "Lg(长度)",
                    dataIndex: "WOOD_LENGTH",
                    width: 110,
                    key: "WOOD_LENGTH",
                },
                {
                    title: "Vol.(方量)",
                    dataIndex: "WOOD_VOLUME",
                    width: 100,
                    key: "WOOD_VOLUME",
                },
                {
                    title: "状态",
                    dataIndex: "GOODS_STATUS",
                    width: 80,
                    key: "GOODS_STATUS",
                },
                {
                    title: "订单号",
                    dataIndex: "ORDER_NO",
                    width: 80,
                    key: "ORDER_NO",
                },
                {
                    title: "置放仓库",
                    dataIndex: "NOW_DEPT",
                    width: 160,
                    key: "NOW_DEPT",
                },
                {
                    title: "合同号",
                    dataIndex: "contract_no",
                    width: 80,
                    key: "contract_no",
                },
                {
                    title: "木种",
                    dataIndex: "timber_type",
                    width: 80,
                    key: "timber_type",
                },
                {
                    title: "车牌号/船名",
                    dataIndex: "plate_no_ship_name",
                    width: 80,
                    key: "plate_no_ship_name",
                },
                {
                    title: "提单号",
                    dataIndex: "lading_bill_no",
                    width: 80,
                    key: "lading_bill_no",
                },
                {
                    title: "集装箱号",
                    dataIndex: "container_no",
                    width: 100,
                    key: "container_no",
                },
                {
                    title: "装船日期",
                    dataIndex: "shipping_date",
                    width: 100,
                    key: "shipping_date",
                },
                {
                    title: "备注",
                    dataIndex: "remark",
                    width: 150,
                    key: "remark",
                },
            ],
        };
    },
    mounted() {
        ipc.removeAllListeners(specialIpcRoute.appUpdater);
        ipc.on(specialIpcRoute.exitApp, (event, result) => {
            localStorage.removeItem('isLoggedIn');
            localStorage.removeItem('userInfo');
        });

        let uri = ipcApiRoute.uploadWoodStockFile;
        let url = uri.split('.').join('/');
        this.action_url = 'http://localhost:7071/' + url;
        this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
    },
    methods: {
        handleDeptChange(value) {
            // 找到当前选中的选项
            const selectedOption = this.deptOptions.find(option => option.value === value);
            if (selectedOption) {
                // 将选项的 label 赋值给 form.NOW_DEPT_NAME
                this.form.NOW_DEPT = selectedOption.label;
            }
        },
        handleFileChange(info) {
            console.log('handleFileChange-----');
            if (this.action_url == '') {
                AMessage.error('http服务未开启');
                return;
            }
            const status = info.file.status;
            if (status !== 'uploading') {
                console.log(info.file);
            }
            if (status === 'done') {
                const uploadRes = info.file.response;
                console.log('uploadRes:', uploadRes)
                AMessage.success(`${info.file.name} 上传成功.`);
            } else if (status === 'error') {
                AMessage.error(`${info.file.name} 上传失败.`);
            }
        },
        beforeUpload(file) {
            console.log('beforeUpload-----', file.size);
            const isLt1M = file.size / 1024 / 1024 < 1;
            if (!isLt1M) {
                AMessage.error('文件大小不能超过 1MB!');
            }
            return isLt1M;
        },
        confirmDelWoodStockDialog(record) {
            this.showDelWoodStockDialog = true;
            this.delWoodId = record.ID;
        },
        async delWoodStock() {
            await ipc.invoke(ipcApiRoute.deleteWoodStock, this.delWoodId);
            AMessage.success('删除成功');
            this.pagination.current = 1;
            this.fetchData();
            this.showDelWoodStockDialog = false;
        },

        cancelDelWoodStock() {
            this.showDelWoodStockDialog = false;
        },

        formatDate(date) {
            let year = date.getFullYear();
            let month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的  
            let day = String(date.getDate()).padStart(2, '0');
            let hours = String(date.getHours()).padStart(2, '0');
            let minutes = String(date.getMinutes()).padStart(2, '0');
            let seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        filterOption(input, option) {
            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
        },
        async handleSearch() {
            this.fetchData();
        },
        async fetchData() {
            const offset = (this.pagination.current - 1) * this.pagination.pageSize;
            const queryData = {
                pageSize: this.pagination.pageSize,
                offset: offset,
                goodsStatus: 0,
                searchText: this.searchText ? '%' + this.searchText + '%' : null,
            };
            console.log("queryData:", queryData);
            const woodStockList = await ipc.invoke(ipcApiRoute.getWoodStockList, queryData);
            console.log("woodStockList:", woodStockList);
            this.data = woodStockList.list;
            this.pagination.total = woodStockList.total;
        },
        handleTableChange(pagination) {
            this.pagination = pagination;
            this.fetchData();
        },
        addWoodStock() {
            this.form = {};
            this.showModal();
        },
        showModal() {
            this.isModalVisible = true;
        },
        handleOk() {
            this.$refs.formRef
                .validate()
                .then(async () => {
                    try {
                        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
                        const result = await ipc.invoke(ipcApiRoute.saveWoodStock, {
                            ...this.form,
                            WOOD_TYPE: 'wood',
                            // 获取当前时间,形式如 yyyy-MM-dd HH:mm:ss
                            CREATE_TIME: this.formatDate(new Date()),
                            // 获取当前登录用户ID
                            CREATE_USER: userInfo.ID,
                            GOODS_STATUS: 0,
                            is_offline: 1
                        });
                        if (result == 'woodNoExist') {
                            AMessage.error("原木编号已存在，请重新输入原木编号");
                            return;
                        }
                        this.fetchData();
                        AMessage.success("保存成功");
                        this.isModalVisible = false;
                    } catch (e) {
                        console.log("保存失败：", e);
                        AMessage.error("保存失败");
                    }
                })
                .catch((error) => {
                    console.log("表单校验失败：", error);
                });
        },
        handleCancel() {
            this.form = {};
            this.isModalVisible = false;
        },


    },
    async created() {
        this.fetchData(); // 初始化时获取数据
        // 根据用户ID 获取部门列表
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        console.log("==================userInfo:", userInfo);
        this.deptOptions = await ipc.invoke(ipcApiRoute.getDeptOptionsByUserId, {
            userId: userInfo.ID,
            type: 'wood'
        });
        console.log("==================this.deptOptions:", this.deptOptions);
    },
};
</script>

<style>
.container {
    padding: 16px;
}

.header {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 16px;
}

.pagination-container {
    text-align: right;
    margin-top: 16px;
}

/* 自定义滚动条 */
.custom-table::-webkit-scrollbar {
    width: 22px;
    height: 50px;
    /* 滚动条宽度 */
}

.custom-table::-webkit-scrollbar-track {
    background: #f1f1f1;
    /* 滚动条轨道 */
}

.custom-table::-webkit-scrollbar-thumb {
    background: #888;
    /* 滚动条滑块 */
    border-radius: 6px;
    /* 圆角 */
}

.custom-table::-webkit-scrollbar-thumb:hover {
    background: #555;
    /* 滚动条滑块 hover 状态 */
}

.custom-table thead>tr>th {
    font-weight: bold;
    /* 表头加粗 */
}
</style>
